/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.meteocal.control;

import it.polimi.meteocal.entity.User;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

@Stateless
public class SearchManager {

    @PersistenceContext
    private EntityManager em;

    /**
     * search in the data base a user according to his email or anything that
     * match with the email, name, surname
     *
     * @param userSearch the string to be searched
     * @return the list of the matching user
     */
    public List<User> search(String userSearch) {
        System.out.println("****************SEARCHMANAGER******************** " + userSearch);
        List<User> result = new ArrayList<>();
        String arraySplit[];
        TypedQuery<User> searchString = em.createQuery("SELECT u FROM User u WHERE (u.name = :user OR u.surname = :user OR u.email LIKE :email)", User.class);
        TypedQuery<User> searchNameSurname = em.createQuery("SELECT u FROM User u WHERE (u.name = :first AND u.surname = :second) OR (u.name = :second AND u.surname = :first)", User.class);

        if (userSearch.contains(" ")) {
            arraySplit = userSearch.split(" ");
            searchNameSurname.setParameter("first", arraySplit[0]);
            searchNameSurname.setParameter("second", arraySplit[1]);
            result.addAll(searchNameSurname.getResultList());
        } else {
            searchString.setParameter("user", userSearch);
            searchString.setParameter("email", "%" + userSearch + "%");
            result.addAll(searchString.getResultList());
        }
        if (result.isEmpty()) {
            result = null;
        }
        return result;
    }
}
